package com.dudu.service.impl;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mortbay.log.Log;
import org.springframework.beans.BeanUtils;

import com.dudu.bean.AccountBean;
import com.dudu.dao.AccountExtendDao;
import com.dudu.dao.PushAccountDao;
import com.dudu.model.AccountExtend;
import com.dudu.model.PushAccount;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.EncryptUtil;
import com.dudu.utils.MD5Utils;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.CommUtils;

/**
 * 账号扩展信息(数据库)
 * 
 * @author gaoxs
 * 
 */
public class AccountExtendServiceImpl implements IAccountExtendService {
    // 日志输出
    private static final Logger log = Logger.getLogger(AccountExtendServiceImpl.class.getSimpleName());
    // 嘟嘟能力扩展数据操作dao
    private AccountExtendDao accountExtendDao = new AccountExtendDao();
    // 用于查询数据用
    private CoreDao coreDao = CoreDaoInvoke.getInstance();
    private PushAccountDao accountDao = new PushAccountDao();

    /**
     * 嘟嘟能力平台其他扩展信息
     * 
     * @param accountBean
     *            账号实体类
     * @return
     */
    @Override
    public JSONObject insertAccountExtend(AccountBean accountBean) {
	log.info("AccountManageServiceImpl.insertAccountExtend 嘟嘟能力平台其他扩展信息");
	// 用于后期返回值
	JSONObject object = new JSONObject();
	try {
	    // 判断传入的bean是否为空
	    if (accountBean != null) {
		AccountExtend accountExtend = new AccountExtend();
		accountExtend = conversion(accountBean);
		// 判断操作的结果
		if (accountExtendDao.insertAccountExtend(coreDao, accountExtend) != -1) {
		    object.put("result", "0");
		    object.put("describe", "组织账号注册成功");
		    object.put("code", "0000");
		} else {
		    object.put("result", "-1");
		    object.put("describe", "组织账号注册失败");
		    object.put("code", "0100");
		}
	    } else {
		object.put("result", "-1");
		object.put("describe", "传入的值为空，请重试");
		object.put("code", "0100");
	    }
	} catch (Exception e) {
	    log.error("AccountManageServiceImpl.insertAccountExtend 嘟嘟能力平台其他扩展信息异常" + e);
	    object.put("result", "-1");
	    object.put("describe", "嘟嘟能力平台其他扩展信息异常" + e);
	    object.put("code", "0100");
	}

	return object;
    }

    /**
     * 更新
     * 
     * @param accountBean
     * @return
     */
    public int updateAccountExtend(AccountBean accountBean) {
	return accountExtendDao.updateAccountExtend(coreDao, conversion(accountBean));
    }

    /**
     * 转化
     * 
     * @param menu
     * @return
     */
    private AccountBean conversion(AccountExtend bean) {
	AccountBean accExtendBean = new AccountBean();
	BeanUtils.copyProperties(bean, accExtendBean);// 源,目的
	// PropertyUtils.copyProperties(dest, orig);//目的,源
	return accExtendBean;
    }

    /**
     * 转化
     * 
     * @param menuBean
     * @return
     */
    private AccountExtend conversion(AccountBean bean) {
	AccountExtend accountExtend = new AccountExtend();
	BeanUtils.copyProperties(bean, accountExtend);// 源,目的
	// PropertyUtils.copyProperties(dest, orig);//目的,源
	return accountExtend;
    }

    /**
     * 根据custAccount账号标识查询账号信息
     * 
     * @param custAccount
     * @return
     */
    @Override
    public AccountBean queryAccountDetailByCustAccount(String custAccount) {
	// log.info("AccountManageServiceImpl.queryAccountDetailByCustAccount 根据custAccount账号标识查询账号信息");
	// 查询并返回的账号信息实体类
	AccountBean accountBean = null;
	try {
	    // 查询获取相应值
	    AccountExtend accountExtend = accountExtendDao.queryAccountExtendByCustAccount(coreDao, custAccount);
	    if (accountExtend != null) {
		accountBean = new AccountBean();
		accountBean = conversion(accountExtend);
	    } else {
		// log.info("根据custAccount="+custAccount+"，未找到相应信息！");
	    }
	} catch (Exception e) {
	    log.error("AccountManageServiceImpl.queryAccountDetailByCustAccount 根据custAccount账号标识查询账号信息异常" + e);
	}
	return accountBean;
    }

    /**
     * 账号的临时密钥获取（更新）接口
     * 
     * @param cust_Account
     *            组织账号标识(计费标识)
     * @param sign
     *            认证码
     * @param timestamp
     *            时间戳
     * @author gaoxs
     * @return
     */
    public JSONObject updateAccountkey(String cust_Account, String sign, String timestamp) {
	// 用于后面返回参数
	JSONObject object = new JSONObject();
	try {

	    // 根据账号标识查询账号信息
	    AccountExtend acount = accountExtendDao.queryAccountExtendByCustAccount(coreDao, cust_Account);
	    if (acount != null) {
		// 获取计算后的认证码
		String signDB = EncryptUtil.sha1Encrypt(cust_Account + acount.getKey_public() + timestamp);
		if (sign.equalsIgnoreCase(signDB)) {
		    String tempKey = MD5Utils.getMd5Value();
		    // 更新临时密钥
		    acount.setKey_private(tempKey);
		    // 更新临时秘钥
		    int upacount = accountExtendDao.updateAccountExtend(coreDao, acount);
		    if (upacount != -1) {
			object.put("result", 0);
			object.put("code", "0000");
			object.put("describe", "success");
			object.put("org_tempKey", tempKey);
		    } else {
			object.put("result", -1);
			object.put("code", "0001");
			object.put("describe", "更新临时密钥异常");
			object.put("org_tempKey", "");
		    }
		} else {
		    object.put("result", -1);
		    object.put("code", "0001");
		    object.put("describe", "参数sign错误");
		    object.put("org_tempKey", "");
		}
	    } else {
		object.put("result", -1);
		object.put("code", "0002");
		object.put("describe", "计费账号不存在");
		object.put("org_tempKey", "");
	    }
	} catch (Exception ex) {
	    object.put("result", -1);
	    object.put("describe", "失败");
	}
	return object;
    }

    /**
     * 增加推送日志
     * 
     * @param bean
     * @return
     */
    public int insertPushNotice(PushAccount bean) {
	return accountDao.insert(coreDao, bean);
    }

    @Override
    public AccountBean qryVersionFour(JSONObject object, String cust_account, String timestamp, String sign) {
	Log.info("load OpenOperateByVersionFour.qryVersionFour 根据cust_account在v4版本查询相关信息");
	AccountBean result = new AccountBean();
	if (!StringUtils.isBlank(cust_account) && cust_account != null) {
	    result = queryAccountDetailByCustAccount(cust_account);
	    if (result != null) {
		// if(checkValidityService.toolsCheckSign(cust_account,result.getKey_private(),timestamp,sign)){
		setData(object, result);
		return result;
		// }
		// else{
		// object.put("result", "-1");
		// object.put("describe", "参数sign或时间错误");
		// object.put("code", "0001");
		// }
	    } else {
		object.put("result", "-1");
		object.put("describe", "未找到相应账户信息！");
		object.put("code", "0002");
	    }
	}
	return new AccountBean();
    }

    private void setData(JSONObject object, AccountBean accountBean) {
	object.put("result", "0");
	object.put("cust_account", accountBean.getAccount_identify());
	object.put("identify", "");
	object.put("publicKey", accountBean.getKey_public());
	object.put("privateKey", accountBean.getKey_private());
	object.put("urlcallstatus", accountBean.getUrl_callstatus());
	object.put("urlticket", accountBean.getUrl_ticket());
	object.put("urlivrdigit", accountBean.getUrl_ivrdigit());
	object.put("urlrecord", accountBean.getUrl_record());
	object.put("linker_phone", accountBean.getLinker_phone());
    }

    @Override
    public boolean checkSign(JSONObject object, String cust_account, String timestamp, String sign, AccountBean result) {
	ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
	if (checkValidityService.toolsCheckSign(cust_account, result.getKey_public(), timestamp, sign)) {
	    setData(object, result);
	    return true;
	} else {
	    object.clear();
	    object.put("result", "-1");
	    object.put("describe", "参数sign或时间错误");
	    object.put("code", "0001");
	}
	return false;
    }

    @Override
    public JSONObject updVersionThree(JSONObject object, String url, String sign, String timestamp, String cust_account) {
	String method = url + "AccountOper/updByAccount.do";
	// String method = "http://localhost:9090/AccountOper/updByAccount.do";
	HashMap<String, String> m = new HashMap<String, String>();
	JSONObject objectreturn = new JSONObject();
	m.put("cust_account", cust_account);
	m.put("timestamp", timestamp);
	m.put("sign", sign);
	m.put("privateKey", object.getString("privateKey"));
	m.put("publicKey", object.getString("publicKey"));
	m.put("urlcallstatus", object.getString("urlcallstatus"));
	m.put("urlticket", object.getString("urlticket"));
	m.put("urlivrdigit", object.getString("urlivrdigit"));
	m.put("urlrecord", "");
	m.put("linker_phone", object.getString("linker_phone"));

	try {
	    String data = CommUtils.getHttpClientResult(method, m);
	    objectreturn = JSONObject.fromObject(data);
	} catch (IOException e) {

	    e.printStackTrace();
	}
	return objectreturn;
    }

    @Override
    public JSONObject qryVersionThree(String cust_account, String url, String timestamp, String sign) {
	String method = url + "AccountOper/qryByAccount.do";
	// String method = "http://localhost:9090/AccountOper/qryByAccount.do";
	HashMap<String, String> m = new HashMap<String, String>();
	m.put("cust_account", cust_account);
	m.put("timestamp", timestamp);
	m.put("sign", sign);
	JSONObject object = new JSONObject();
	try {
	    String data = CommUtils.getHttpClientResult(method, m);
	    object = JSONObject.fromObject(data);
	} catch (IOException e) {

	    e.printStackTrace();
	}
	return object;
    }

}
